//
//  YXYComposePicture.swift
//  SinaWeibo
//
//  Created by 袁向阳 on 16/7/3.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit

private let ComposePictureCell = "ComposePictureCell"
private let itemMargin: CGFloat = 5

class YXYComposePicture: UICollectionView {
    
    // 流水布局
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    // 图片数组
    var imagesArray: [UIImage] = [UIImage]()
    // 弹出相册
    var closure:(()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 添加子控件
    private func setUpUI () {
        backgroundColor = UIColor.whiteColor()
        self.dataSource = self
        self.delegate = self
        self.hidden = true
        
        let itemWH = (kWidth - 2*10 - 2*itemMargin) / 3
        flowLayout.itemSize = CGSize(width: itemWH, height: itemWH)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        
        registerClass(YXYComposePictureCell.self, forCellWithReuseIdentifier: ComposePictureCell)
    }
    
    // MARK: - 供外界插入图片的
    func addImage(image: UIImage) {
        
        // 不能超过 9 张
        if imagesArray.count > 9 {
            imagesArray.removeFirst()
        }else {
            imagesArray.append(image)
        }
        
        if imagesArray.count > 0 {
            self.hidden = false
        }
        
        reloadData()
    }
}

extension YXYComposePicture: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if imagesArray.count == 0 || imagesArray.count == 9 {
            return imagesArray.count
        }else {
            return imagesArray.count + 1
        }
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ComposePictureCell, forIndexPath: indexPath) as! YXYComposePictureCell
        
        if indexPath.item == imagesArray.count {
            cell.image = nil
        }else {
            cell.image = imagesArray[indexPath.item]
        }
        
        
        cell.pictureCellDeleteBtnClosure = {
            self.imagesArray.removeAtIndex(indexPath.item)
            self.reloadData()
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if indexPath.item == imagesArray.count {
            closure?()
        }
    }
}

class YXYComposePictureCell : UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteBtn.hidden = true
            }else {
                imageView.image = image
                // 解决cell重用的问题
                imageView.highlightedImage = nil
                deleteBtn.hidden = false
            }
        }
    }
    
    // 取消按钮的闭包
    var pictureCellDeleteBtnClosure:(()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 添加子控件
    private func setUpUI () {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteBtn)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.top.equalTo(imageView)
        }
    }
    
    lazy var imageView: UIImageView = UIImageView()
    
    lazy var deleteBtn: UIButton = {
        let button = UIButton()
        button.hidden = true
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.sizeToFit()
        button.addTarget(self, action: "clickDeleteBtn:", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    // MARK: - 图片右上角的取消按钮
    @objc private func clickDeleteBtn (button: UIButton) {
        pictureCellDeleteBtnClosure?()
    }
}


